package org.jamin.lending.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jamin.lending.domain.BJUIAjaxResult;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.log.Log;

public class AuserStatusInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		Object obg = WebUtils.getSessionAttribute(request, "auser");
		if(obg == null){
			String requested = request.getHeader("X-Requested-With");
			if(requested == null){
				response.sendRedirect(request.getContextPath()+"/admin/login");
			}else if(requested.equals("XMLHttpRequest")){
				BJUIAjaxResult ajaxResult = BJUIAjaxResult.createFail("您的登录已经超时，请重新登录");
				ajaxResult.setStatusCode(301);
				response.setHeader("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
				response.setCharacterEncoding("UTF-8");
				PrintWriter printWriter = response.getWriter();
				printWriter.println(new ObjectMapper().writeValueAsString(ajaxResult));
				
			}
			return false;
		}
		return true;
	}

}
